package any.incubator.xstream;

import any.AnyVisitor;
import any.SequentialAny;

import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;


public class AnyConverter implements Converter {

	@SuppressWarnings("rawtypes")
    public boolean canConvert(Class type) {
		return SequentialAny.class.isAssignableFrom(type);
	}

	public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
		SequentialAny any = (SequentialAny)source;
		any.accept(new Visitor(writer));
	}

	public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
		return null;
	}
	
	class Visitor implements AnyVisitor<SequentialAny> {
		private final HierarchicalStreamWriter writer;
		Visitor(HierarchicalStreamWriter writer) {
			this.writer = writer;
		}
		public boolean visit(String key, int index, SequentialAny any) {
			writer.setValue(any.toAny().toString());
			return true;
		}
		public boolean beginVisit(String key, int index, SequentialAny any) {
			return true;
		}
		public boolean endVisit(String key, int index, SequentialAny any) {
	        return true;
        }
	}

}
